//
// Created by 周圳元 on 2023/3/29.
//
#include "../../include/user.h"
#include "../qq_sqlite3/sql_user.h"
#include "../../include/json_chat.h"
#include "../../include/group_db.h"
#include "../qq_sqlite3/sql_group_member.h"
#include "../qq_sqlite3/sql_user_friend.h"
#include "../qq_sqlite3/sql_chart_content.h"
#include <stdlib.h>
#define ERROR_FUNC strcpy(rep, message_init(NORMAL_ERROR,"{}","失败"))
#define SUCCESS_FUNC strcpy(rep, message_init(SUCCESS,"{}","成功"))
int login(char *username,char *password) {

    return 0;
}

char *text_to_num(int id,char *ch) {
    return sprintf(ch,"%d",id);
}

// 0则有这个好友，-1，则没有
int have_friend(int id,char *ch) {
}

// 判断是否有这个用户
// 0则有，-1没有
int have_user(char*username) {
    user_t user;
    int re = get_user_by_user_name(username,&user);
    return re > 0?0:-1;
}

int registe(char *username,char *password) {
    user_t user;
    strcpy(user.user_name,username);
    strcpy(user.passwd,password);
    return add_user(&user);
}

//void content_set(char *json,content_t *content) {
//     *content = {.sender_id=json_get_int(req,"user_id"),
//            .receiver_id=json_get_int(req,"receiver_id")};
//    strcpy(content->content, json_get_string(req,"content"));
//    strcpy(content->sender_name, json_get_string(req,"sender_name"));
//    strcpy(content->receiver_name, json_get_string(req,"receiver_name"));
//}

char * get_username(char *json) {
    return json_get_string(json,"user_name");
}

char * get_passwd(char *json) {
    return json_get_string(json,"passwd");
}

int user_handle(int action,char *req,char *rep,client_t client[],int num,int len) {
//    printf("断电1");
    switch(action) {
        case USER_LOGIN:
        {
            user_t user;
            char *username = get_username(req);
            char *passwd = get_passwd(req);
            int a = get_user_by_user_name(username,&user);
            printf("a: %d pass %s \n",a,user.passwd);
            if (a <= 0) {
                ERROR_FUNC;
                break;
            }
            char t[40];
            bzero(t,40);
            sprintf(t,"%d",user.user_id);
            if (strcmp(passwd,user.passwd) == 0) {
                strcpy(rep,message_init(SUCCESS,"{}",t));
		//保存用户信息
		client[num].user = user;
		printf("保存用户登录信息 user_id: %d username: %s passwd:  %s",user.user_id,user.user_name,user.passwd);
    
                break;
            }
            ERROR_FUNC;
            break;
        }
        case USER_REGISTER:
        {
            user_t user;
            user.user_id = 0;
            char *username = get_username(req);
            printf("客户端的usernmae : %s\n",username);
            int a = get_user_by_user_name(username,&user);
            printf("查询数据库中 %d \n",a);
            // 如果有数据说明含有重复的用户名
            if (user.user_id != 0) {
                strcpy(rep, message_init(LOGIN_ERROR,"{}","含有重复用户名"));
                break;
            }

            int ret = registe(get_username(req),json_get_string(req,"passwd"));
            if (ret) {
                ERROR_FUNC;
                break;
            }
            SUCCESS_FUNC;
            break;
        }
        case USER_ADD_F:
        {
            int user_id = json_get_int(req,"user_id");
            int friend_id = json_get_int(req,"fr_id");
            if (user_id == friend_id) {
                ERROR_FUNC;
            }
            int ret,test;
            if ((ret = add_user_friend(user_id,friend_id)) == -1) {
                ERROR_FUNC;
                break;
            } else {
                if ((test = add_user_friend(friend_id,user_id)) == -1) {
                    ERROR_FUNC;
                    break;
                }
            }
            SUCCESS_FUNC;
            break;
        }
        case USER_FIND_ONLINE:
        {

            // 查看在线好友
            break;
        }
        case USER_FIND_F_ALL:
        {
            user_t fret[100];
            int len = get_user_friend_by_id(json_get_int(req,"user_id"),fret);
            printf("你的名字是 ！%s \n",fret[0].user_name);
            printf("你的名字是 ！%s \n",fret[1].user_name);
            char *json[100];
            for (int i = 0;i <=99;i++) {
                json[i] = (char *)(malloc(sizeof(char) * 100));
            }
            if (len < 0) {
                ERROR_FUNC;
            } else if (len == 0) {
//                ERROR_FUNC;
            } else {
                for (int i = len-1;i >= 0;i--) {
                    char * p = user_to_json(fret[i]);
                    strcpy(json[i],p);
                }
                char i_len[10];
//                printf("test2 :%s \n",json[1]);
                sprintf(i_len,"%d",len);
                strcpy(rep, message_init(SUCCESS,array_to_json(json,len),i_len));
           //     { \\"user_name\\": \\"qweqesss\\", \\"user_id\\": 3, \\"create_time\\": 239407880 }, { \\"user_name\\": \\"qweqwe\\", \\"user_id\\": 2, \\"create_time\\": 239407880 }

//                char *s[100];
//                for (int i = 0;i <=99;i++) {
//                    s[i] = (char *)(malloc(sizeof(char) * 100));
//                }
//                int j = json_to_array(s,array_to_json(json,len),80);
//                for (int x = 0;x < j;x++) {
//                    printf("字符串是 %s \n",s[x]);
//                    printf("取值 %s", json_get_string(s[x],"user_name"));
//                }
//                for (int i = 0;i <=99;i++) {
//                    free(json[i]);
//                }
            }
            // 查看所有好友
            break;
        }
        case USER_FIND_F_BY_NAME:
        {
            //根据用户名搜索好友
            user_t user;
            if (get_user_by_user_name(get_username(req),&user)) {
                break;
            }
            strcpy(rep, user_to_json(user));
            break;
        }
        case USER_FIND_BY_NAME:
        {
            user_t user;
            user_t ret;
            char ret2[40];
            //根据用户名搜索用户:
            if (get_user_by_user_name(get_username(req),&user) <= 0) {
                strcpy(rep, message_init(NORMAL_ERROR,"{}","不存在该用户"));
                break;
            }
            strcpy(ret.user_name,user.user_name);
            ret.user_id = user.user_id;
            text_to_num(ret.user_id,ret2);
            strcpy(rep,message_init(SUCCESS, user_to_json(ret),ret2));
            break;
        }
        case USER_DELETE_F:
        {   //删除好友

            int user_id = json_get_int(req,"user_id");
            int friend_id = json_get_int(req,"fr_id");

            if (user_id == friend_id) {
                ERROR_FUNC;
                break;
            }
            printf("userID: frientID%d %d \n",user_id, friend_id);
            if (del_user_friend(user_id,friend_id) == -1) {
                ERROR_FUNC;
                break;
            }
            if (del_user_friend(friend_id,user_id) == -1) {
                ERROR_FUNC;
                break;
            }
            SUCCESS_FUNC;
            break;
        }
        case USER_CRT_GROUP:
        {   //用户创建群组
//            printf("断点6");
            // 用户创建组
            group_t group;
            group.creator_id = json_get_int(req,"user_id");
            strcpy(group.group_name, json_get_string(req,"group_name"));
            strcpy(group.creator_name, json_get_string(req,"creator_name"));
            strcpy(group.remark, json_get_string(req,"remark"));
            if (insert_group(group)) {
                ERROR_FUNC;
                break;
            }

            //int len;
            //group_t group1 = {.creator_id=group.creator_id,.group_name="",.creator_name="",.group_id=0,.remark=""};
            //group_t * group2 = select_group(group1,&len,0);

            gmember_t gmember = {.group_id = get_insert_id(),.group_member_id=group.creator_id};
            if (add_group_member(&gmember)) {
                ERROR_FUNC;
                break;
            }
            SUCCESS_FUNC;
            break;
        }
        case USER_JOIN_GROUP:
        // 群组加入用户
        {
            //判断小组成员是否在组内
            int group_id = json_get_int(req,"group_id");
            int member_id = json_get_int(req,"member_id");
            gmember_t gmember = {.group_member_id=member_id,.group_id=group_id};
            // 用户加入群组
            if (add_group_member(&gmember)) {
                ERROR_FUNC;
                break;
            }
            SUCCESS_FUNC;
            break;
        } case USER_GET_GROUP:{
	    //获取加入的群组        
            int user_id = json_get_int(req,"user_id");
	    group_t gs[100];
            if (get_join_groups(user_id,&gs)) {
                ERROR_FUNC;
                break;
            }
            SUCCESS_FUNC;
            break;
        }

        case USER_SEND_MESSAGE_USER: {
	    int receiver_id = json_get_int(req,"fr_id");
	    int friend_socket_id;
	    //判断好友是否登录
	    int flag = -1;
	    int i;
	    for(i = 0;i < len;i++) {
		if(client[i].user.user_id == receiver_id) {
		    friend_socket_id = client[i].client;
		    flag = 0;
		    break;	    
		}
	    }		
	   
	    if(flag) {
                strcpy(rep, message_init(USER_SEND_MESSAGE_USER_OFF,"{}","好友不在线"));
		break;	    
	    } 
	    	    
            // 用户私发消息
	    char *text = json_get_string(req,"content");
	    char *sender = json_get_string(req,"user_name");
	    printf("=================================给好友发送信息开始==========================================\n");
//            pthread_mutex_lock(m);
	    send(friend_socket_id,text,strlen(text),0);
//            pthread_mutex_unlock(m);
	    printf("用户 %s 给好友 %s 发送 %s\n",sender,client[i].user.user_name,text);
	    printf("=================================给好友发送信息结束==========================================\n");
            content_t content = {.sender_id=json_get_int(req,"user_id"),
                                 .receiver_id=receiver_id,
                                 .type=0};
            strcpy(content.content, text);
            strcpy(content.sender_name, json_get_string(req,"sender_name"));
            strcpy(content.receiver_name, client[i].user.user_name);
            add_chart_content(&content);
	    SUCCESS_FUNC;
            break;
        }
        case USER_SEND_MESSAGE_GROUP: {
            printf("=================================群聊开始==========================================\n");
            // 用户群发消息
            int group_id = json_get_int(req,"group_id");
            int user_id = json_get_int(req,"user_id");
            char *text = json_get_string(req,"content");
            char *user_name = json_get_string(req,"user_name");
            //获取小组成员
            int members[100];
            int ret = get_group_member(group_id,&members);
            if(ret < 2) {
                strcpy(rep,message_init(USER_GROUP_SEND_NO_FRIEND,"{}","请先添加群聊好友"));
                break;
            }
            for(int i = 0;i < ret;i++) {
                for(int j = 0;j < len;j++) {
                    //跳过本人
                    if(members[i] == user_id || client[j].user.user_id == user_id) {
                        continue;
                    }
                    if(members[i] == client[j].user.user_id) {
                        send(client[j].client,text,strlen(text),0);
                        printf("群聊用户:%s 给群聊用户:%s 发送 %s\n",user_name,client[j].user.user_name,text);
                        //保存聊天记录
                        content_t content = {.sender_id=user_id,
                        .receiver_id = client[j].user.user_id,
                        .type=1};
                        strcpy(content.content, text);
                        strcpy(content.sender_name, user_name);
                        strcpy(content.receiver_name, client[j].user.user_name);
                        add_chart_content(&content);
                    }
                }
	    }
	    printf("=================================群聊结束==========================================\n");
            break;
        }
        case GROUP_DELETE_USER:
        {   //群中删除用户
            break;
        }
        case USER_OUT_ONLINE:
        {   //用户注销
            break;
        }
        case SERVER_SEND_ALL:
        {

            break;
        }
        
    }
    return 1;
}

